﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using ObjectAttribute.Model;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
using static Mysqlx.Notice.Warning.Types;

namespace ObjectAttribute
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.textBoxServer.Text = "127.0.0.1";
            this.textBoxUser.Text = "root";
            this.textBoxPassword.Text = "123456";
            this.textBoxDatabase.Text = "lims";

            // 按钮点击事件
            //buttonConnect.Click += buttonConnect_Click;
            buttonInsert.Click += buttonInsert_Click;
            button1.Click += button1_Click;
        }

        private string GetConnectionString()
        {
            string server = textBoxServer.Text.Trim();
            string user = textBoxUser.Text.Trim();
            string password = textBoxPassword.Text.Trim();
            string database = textBoxDatabase.Text.Trim();

            if (
                string.IsNullOrEmpty(server)
                || string.IsNullOrEmpty(user)
                || string.IsNullOrEmpty(password)
                || string.IsNullOrEmpty(database)
            )
            {
                throw new InvalidOperationException("请填写所有的数据库连接信息！");
            }

            return $"server={server};user={user};password={password};database={database};charset=utf8mb4";
        }

        private void buttonConnect_Click(object sender, EventArgs e)
        {
            string connectionString = GetConnectionString();
            try
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    connection.Open();
                    MessageBox.Show("数据库连接成功！");
                }
            }
            catch (MySqlException ex)
            {
                MessageBox.Show($"连接失败: {ex.Message}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生错误: {ex.Message}");
            }
        }

        private void buttonInsert_Click(object sender, EventArgs e)
        {
            string registerCode = textBoxRegisterCode.Text.Trim();
            string readType = textBoxReadType.Text.Trim();

            if (string.IsNullOrEmpty(registerCode) || string.IsNullOrEmpty(readType))
            {
                MessageBox.Show("寄存器编码和数据类型不能为空！");
                return;
            }

            string connectionString = GetConnectionString();
            List<ObjectAttributeDto> dtoList = new List<ObjectAttributeDto>();

            try
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    connection.Open();

                    using (MySqlTransaction transaction = connection.BeginTransaction())
                    {
                        try
                        {
                            // 获取 objectGuid
                            string query1 =
                                "SELECT * FROM t_equipment WHERE name LIKE @registerCode";
                            ObjectAttributeDto objectAttributeDto = new ObjectAttributeDto
                            {
                                Guid = Guid.NewGuid().ToString()
                            };

                            using (
                                MySqlCommand command1 = new MySqlCommand(
                                    query1,
                                    connection,
                                    transaction
                                )
                            )
                            {
                                command1.Parameters.AddWithValue("@registerCode", registerCode);

                                using (MySqlDataReader reader = command1.ExecuteReader())
                                {
                                    if (reader.Read())
                                    {
                                        objectAttributeDto.ObjectGuid = reader["guid"].ToString();
                                    }
                                    else
                                    {
                                        MessageBox.Show("没有相关记录在 t_equipment 表中！");
                                        return;
                                    }
                                }
                            }

                            // 查询寄存器状态数据
                            string query2 =
                                "SELECT * FROM t_register_state_key WHERE register_code = @registerCode AND read_type = @readType";

                            using (
                                MySqlCommand command2 = new MySqlCommand(
                                    query2,
                                    connection,
                                    transaction
                                )
                            )
                            {
                                command2.Parameters.AddWithValue("@registerCode", registerCode);
                                command2.Parameters.AddWithValue(
                                    "@readType",
                                    Convert.ToInt16(readType)
                                );

                                using (MySqlDataReader reader = command2.ExecuteReader())
                                {
                                    while (reader.Read())
                                    {
                                        dtoList.Add(
                                            new ObjectAttributeDto
                                            {
                                                Guid = Guid.NewGuid().ToString(),
                                                ObjectGuid = objectAttributeDto.ObjectGuid,
                                                ShowTitle = reader["state_name"].ToString(),
                                                RecordType = (int)reader["read_type"],
                                                ValueType = reader["value_type"].ToString(),
                                                RegisterStateKey = reader["state_key"].ToString(),
                                                RegisterCode = reader["register_code"].ToString(),
                                                RegisterStateGuid = reader["guid"].ToString(),
                                                CreateTime = DateTime.Now,
                                                UpdateTime = DateTime.Now,
                                                CreateUser = "lkc",
                                                UpdateUser = "lkc",
                                                Valid = true
                                            }
                                        );
                                    }
                                }
                            }

                            // 插入数据
                            string insertQuery =
                                @"
                                INSERT INTO t_object_attribute (
                                    guid, object_guid, record_type, show_title, value_type, create_time, update_time,
                                    create_user, update_user, valid, dept_guid, register_code, register_state_key,
                                    show_value, register_state_guid, `order`, log, log_rate, name, warning_guid,
                                    related_attribute_guid, `type`, is_default
                                ) 
                                VALUES (
                                    @Guid, @ObjectGuid, @RecordType, @ShowTitle, @ValueType, @CreateTime, @UpdateTime,
                                    @CreateUser, @UpdateUser, @Valid, @DeptGuid, @RegisterCode, @RegisterStateKey,
                                    @ShowValue, @RegisterStateGuid, @Order, @Log, @LogRate, @Name, @WarningGuid,
                                    @RelatedAttributeGuid, @Type, @IsDefault
                                )";

                            foreach (var dto in dtoList)
                            {
                                using (
                                    MySqlCommand insertCommand = new MySqlCommand(
                                        insertQuery,
                                        connection,
                                        transaction
                                    )
                                )
                                {
                                    insertCommand.Parameters.AddWithValue("@Guid", dto.Guid);
                                    insertCommand.Parameters.AddWithValue(
                                        "@ObjectGuid",
                                        dto.ObjectGuid
                                    );
                                    insertCommand.Parameters.AddWithValue(
                                        "@RecordType",
                                        dto.RecordType
                                    );
                                    insertCommand.Parameters.AddWithValue(
                                        "@ShowTitle",
                                        dto.ShowTitle
                                    );
                                    insertCommand.Parameters.AddWithValue(
                                        "@ValueType",
                                        dto.ValueType
                                    );
                                    insertCommand.Parameters.AddWithValue(
                                        "@CreateTime",
                                        dto.CreateTime
                                    );
                                    insertCommand.Parameters.AddWithValue(
                                        "@UpdateTime",
                                        dto.UpdateTime
                                    );
                                    insertCommand.Parameters.AddWithValue(
                                        "@CreateUser",
                                        dto.CreateUser
                                    );
                                    insertCommand.Parameters.AddWithValue(
                                        "@UpdateUser",
                                        dto.UpdateUser
                                    );
                                    insertCommand.Parameters.AddWithValue("@Valid", dto.Valid);
                                    insertCommand.Parameters.AddWithValue(
                                        "@DeptGuid",
                                        DBNull.Value
                                    );
                                    insertCommand.Parameters.AddWithValue(
                                        "@RegisterCode",
                                        dto.RegisterCode
                                    );
                                    insertCommand.Parameters.AddWithValue(
                                        "@RegisterStateKey",
                                        dto.RegisterStateKey
                                    );
                                    insertCommand.Parameters.AddWithValue(
                                        "@ShowValue",
                                        DBNull.Value
                                    );
                                    insertCommand.Parameters.AddWithValue(
                                        "@RegisterStateGuid",
                                        dto.RegisterStateGuid
                                    );
                                    insertCommand.Parameters.AddWithValue("@Order", DBNull.Value);
                                    insertCommand.Parameters.AddWithValue("@Log", DBNull.Value);
                                    insertCommand.Parameters.AddWithValue("@LogRate", DBNull.Value);
                                    insertCommand.Parameters.AddWithValue("@Name", DBNull.Value);
                                    insertCommand.Parameters.AddWithValue(
                                        "@WarningGuid",
                                        DBNull.Value
                                    );
                                    insertCommand.Parameters.AddWithValue(
                                        "@RelatedAttributeGuid",
                                        DBNull.Value
                                    );
                                    insertCommand.Parameters.AddWithValue("@Type", DBNull.Value);
                                    insertCommand.Parameters.AddWithValue(
                                        "@IsDefault",
                                        DBNull.Value
                                    );

                                    insertCommand.ExecuteNonQuery();
                                }
                            }

                            transaction.Commit();
                            MessageBox.Show("数据插入成功！");
                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();
                            MessageBox.Show($"事务失败: {ex.Message}");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"错误: {ex.Message}");
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string connectionString = GetConnectionString();

            // 查询语句
            string query = "SELECT code FROM t_register";

            // 插入语句
            string insertQuery =
                @"
                INSERT INTO t_equipment
                (
                    guid, name, code, installation_date, last_maintenance_time, next_maintenance_time,
                    type, production_company, additional_info, create_time, update_time, create_user,
                    update_user, valid, dept_guid, position, space_guid, status, administrator_guid,
                    batch_number, online_status_config, maintenance_company_guid, use_type, be_controlled,
                    system_classification, register_code, register_state_key, register_state_guid,
                    installer, supplier, purchaser, purchase_time
                )
                VALUES
                (
                    @Guid, @Name, @Code, @InstallationDate, @LastMaintenanceTime, @NextMaintenanceTime,
                    @Type, @ProductionCompany, @AdditionalInfo, @CreateTime, @UpdateTime, @CreateUser,
                    @UpdateUser, @Valid, @DeptGuid, @Position, @SpaceGuid, @Status, @AdministratorGuid,
                    @BatchNumber, @OnlineStatusConfig, @MaintenanceCompanyGuid, @UseType, @BeControlled,
                    @SystemClassification, @RegisterCode, @RegisterStateKey, @RegisterStateGuid,
                    @Installer, @Supplier, @Purchaser, @PurchaseTime
                )";

            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                try
                {
                    connection.Open();

                    // 缓存查询结果
                    List<string> codes = new List<string>();
                    using (MySqlCommand command = new MySqlCommand(query, connection))
                    {
                        using (MySqlDataReader reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                codes.Add(reader.GetString("code"));
                            }
                        }
                    }

                    // 插入数据
                    foreach (string code in codes)
                    {
                        var equipment = new
                        {
                            Guid = Guid.NewGuid().ToString(),
                            Name = code,
                            Code = code,
                            InstallationDate = DateTime.Now,
                            LastMaintenanceTime = DateTime.Now.AddMonths(-1),
                            NextMaintenanceTime = DateTime.Now.AddMonths(6),
                            Type = "d1fb3d587a274abc7207900bec398c2f",
                            ProductionCompany = "",
                            AdditionalInfo = "{}",
                            CreateTime = DateTime.Now,
                            UpdateTime = DateTime.Now,
                            CreateUser = "lkc",
                            UpdateUser = "lkc",
                            Valid = 1,
                            DeptGuid = "",
                            Position = "",
                            SpaceGuid = "",
                            Status = 1,
                            AdministratorGuid = "",
                            BatchNumber = "",
                            OnlineStatusConfig = "",
                            MaintenanceCompanyGuid = "",
                            UseType = 0,
                            BeControlled = 1,
                            SystemClassification = "",
                            RegisterCode = code,
                            RegisterStateKey = "",
                            RegisterStateGuid = "",
                            Installer = "",
                            Supplier = "",
                            Purchaser = "",
                            PurchaseTime = DateTime.Now,
                        };

                        using (MySqlCommand insertCommand = new MySqlCommand(insertQuery, connection))
                        {
                            insertCommand.Parameters.AddWithValue("@Guid", equipment.Guid);
                            insertCommand.Parameters.AddWithValue("@Name", equipment.Name);
                            insertCommand.Parameters.AddWithValue("@Code", equipment.Code);
                            insertCommand.Parameters.AddWithValue("@InstallationDate", equipment.InstallationDate);
                            insertCommand.Parameters.AddWithValue("@LastMaintenanceTime", equipment.LastMaintenanceTime);
                            insertCommand.Parameters.AddWithValue("@NextMaintenanceTime", equipment.NextMaintenanceTime);
                            insertCommand.Parameters.AddWithValue("@Type", equipment.Type);
                            insertCommand.Parameters.AddWithValue("@ProductionCompany", equipment.ProductionCompany);
                            insertCommand.Parameters.AddWithValue("@AdditionalInfo", equipment.AdditionalInfo);
                            insertCommand.Parameters.AddWithValue("@CreateTime", equipment.CreateTime);
                            insertCommand.Parameters.AddWithValue("@UpdateTime", equipment.UpdateTime);
                            insertCommand.Parameters.AddWithValue("@CreateUser", equipment.CreateUser);
                            insertCommand.Parameters.AddWithValue("@UpdateUser", equipment.UpdateUser);
                            insertCommand.Parameters.AddWithValue("@Valid", equipment.Valid);
                            insertCommand.Parameters.AddWithValue("@DeptGuid", equipment.DeptGuid);
                            insertCommand.Parameters.AddWithValue("@Position", equipment.Position);
                            insertCommand.Parameters.AddWithValue("@SpaceGuid", equipment.SpaceGuid);
                            insertCommand.Parameters.AddWithValue("@Status", equipment.Status);
                            insertCommand.Parameters.AddWithValue("@AdministratorGuid", equipment.AdministratorGuid);
                            insertCommand.Parameters.AddWithValue("@BatchNumber", equipment.BatchNumber);
                            insertCommand.Parameters.AddWithValue("@OnlineStatusConfig", equipment.OnlineStatusConfig);
                            insertCommand.Parameters.AddWithValue("@MaintenanceCompanyGuid", equipment.MaintenanceCompanyGuid);
                            insertCommand.Parameters.AddWithValue("@UseType", equipment.UseType);
                            insertCommand.Parameters.AddWithValue("@BeControlled", equipment.BeControlled);
                            insertCommand.Parameters.AddWithValue("@SystemClassification", equipment.SystemClassification);
                            insertCommand.Parameters.AddWithValue("@RegisterCode", equipment.RegisterCode);
                            insertCommand.Parameters.AddWithValue("@RegisterStateKey", equipment.RegisterStateKey);
                            insertCommand.Parameters.AddWithValue("@RegisterStateGuid", equipment.RegisterStateGuid);
                            insertCommand.Parameters.AddWithValue("@Installer", equipment.Installer);
                            insertCommand.Parameters.AddWithValue("@Supplier", equipment.Supplier);
                            insertCommand.Parameters.AddWithValue("@Purchaser", equipment.Purchaser);
                            insertCommand.Parameters.AddWithValue("@PurchaseTime", equipment.PurchaseTime);
                            insertCommand.ExecuteNonQuery();
                        }
                    }

                    MessageBox.Show("数据插入成功！");
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

    }
}
